<?php
$con = mysqli_connect('localhost', 'root', 'root', 'project-manage');

$paid_data = [];
$datas = [];
$sql = 'select * from ba_apply_reimbursement where audit_state = 3';
$result = $con->query($sql);
res2data($result);
$sql = 'select * from ba_apply_advance where audit_state = 3';
$result = $con->query($sql);
res2data($result);
$sql = 'select * from ba_apply_payment where audit_state = 3';
$result = $con->query($sql);
res2data($result);

function res2data($result) {
    global $paid_data;
    while ($row = mysqli_fetch_assoc($result)){
        try {
            $feeitems = json_decode($row['feeitems'], true);
            if(!empty($feeitems)) {
                foreach ($feeitems as $v) {
                    $temp = array_merge($v, ['project_id' => $row['project_id']]);
//                    $datas[] = $temp;
                    $key = $v["feeitem_id"].'_'.$row['project_id'];
                    if(isset($paid_data[$key])){
                        $paid_data[$key]['amount'] = bcadd($paid_data[$key]['amount'], $v['amount']);
                    } else {
                        $paid_data[$key] = [
                            'feeitem_id' => $v['feeitem_id'],
                            'amount' => $v['amount'],
                            'project_id' => $row['project_id']
                        ];
                    }
                    echo implode('-', $temp).PHP_EOL;
                }
            }
        }catch (Exception $e){

        }

    }
}
foreach ($paid_data as $v){
    $sql = 'update ba_project_feeitem set paid = '.$v['amount'].' where feeitem_id = '.$v['feeitem_id'].' and project_id = '.$v['project_id'];
    $con->query($sql);
}
mysqli_close($con);
var_dump($paid_data);